package com.yq.topCode;

/**
 * @ClassName Solution707MyLinkList
 * @Description 设计单链表
 * @Author yaoqiang
 * @Date 2022/8/4 13:52
 * @Version 1.0
 */
public class Solution707MyLinedList {
    public static void main(String[] args) {
        Solution707MyLinedList obj=new Solution707MyLinedList();
        int[] arr=new int[]{1,2,3,4,5};
        obj.addbyints(arr);
        System.out.println(obj.get(0));
    }

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */
    int size;
    ListNode head;

    public Solution707MyLinedList() {
        size=0;
        head=new ListNode(0);
    }
    public int get(int index){
        if(index<0 ||index >size) return -1;
        ListNode cur=head;
        for(int i=0;i<index+1;++i) cur=cur.next;
        return cur.val;
    }
    public void addAtHead(int val){
        addAtIndex(0,val);
    }
    public  void addAtTail(int val){
        addAtIndex(size,val);
    }

    public void addAtIndex(int index,int val){
        ++size;
        ListNode pred=head;
        for (int i=0;i<index;++i) pred=pred.next;
        ListNode toAdd=new ListNode(val);
        toAdd.next=pred.next;
        pred.next=toAdd;
    }
    public void deleteAtIndex(int index){
        if(index<0 || index>=size) return;
        size--;
        ListNode pred=head;
        for (int i=0;i<index;++i) pred=pred.next;
        pred.next=pred.next.next;
    }
    public void addbyints(int[] arrs){
        for (int i=0;i<arrs.length;i++){
            addAtTail(arrs[i]);
        }
    }
}
